package com.kuaifawu.lwnlawyerclient.Lib.photoselector.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kuaifawu.lwnlawyerclient.Lib.KFWActivityCenter;
import com.kuaifawu.lwnlawyerclient.Lib.KFWTools;
import com.kuaifawu.lwnlawyerclient.Lib.ToastView_custom;
import com.kuaifawu.lwnlawyerclient.Lib.photoselector.domain.PhotoSelectorDomain;
import com.kuaifawu.lwnlawyerclient.Lib.photoselector.model.AlbumModel;
import com.kuaifawu.lwnlawyerclient.Lib.photoselector.model.PhotoModel;
import com.kuaifawu.lwnlawyerclient.Lib.photoselector.util.AnimationUtil;
import com.kuaifawu.lwnlawyerclient.Lib.photoselector.util.CommonUtils;
import com.kuaifawu.lwnlawyerclient.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;


public class PhotoSelectorActivity extends Activity implements PhotoItem.onItemClickListener, PhotoItem.onPhotoItemCheckedListener,
        OnItemClickListener, OnClickListener {

    public static final int REQUEST_PHOTO = 0;
    private static final int REQUEST_CAMERA = 1;

    public static final String RECCENT_PHOTO = "最近照片";

    private GridView gvPhotos;
    private ListView lvAblum;
    private Button btnOk;
    private TextView tvAlbum, tvPreview;
    private PhotoSelectorDomain photoSelectorDomain;
    private PhotoSelectorAdapter photoAdapter;
    private AlbumAdapter albumAdapter;
    private RelativeLayout layoutAlbum;
    private ArrayList<PhotoModel> selected;
   // private ArrayList<PhotoModel> deletCompress;
    private boolean isScanPhoto=false;
    private  ArrayList<PhotoModel> scanList=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(KFWActivityCenter.getInstance().getArray_model() != null){
            KFWActivityCenter.getInstance().getArray_model().clear();
        }

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_photoselector);

        DisplayImageOptions defaultDisplayImageOptions = new DisplayImageOptions.Builder()
                .considerExifParams(true)
                .resetViewBeforeLoading(true)
                .showImageOnLoading(R.drawable.ic_picture_loading)
                .showImageOnFail(R.drawable.ic_picture_loadfailed)
                .delayBeforeLoading(0)
                .build(); //
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                .defaultDisplayImageOptions(defaultDisplayImageOptions).memoryCacheExtraOptions(480, 800)
                .threadPoolSize(5).build();
        ImageLoader.getInstance().init(config);

        photoSelectorDomain = new PhotoSelectorDomain(getApplicationContext());

        selected = new ArrayList<PhotoModel>();


        //tvTitle = (TextView) findViewById(R.id.tv_title_lh);
        gvPhotos = (GridView) findViewById(R.id.gv_photos_ar);
        lvAblum = (ListView) findViewById(R.id.lv_ablum_ar);
        btnOk = (Button) findViewById(R.id.btn_right_lh);
        tvAlbum = (TextView) findViewById(R.id.tv_album_ar);
        tvPreview = (TextView) findViewById(R.id.tv_preview_ar);
        layoutAlbum = (RelativeLayout) findViewById(R.id.layout_album_ar);

        btnOk.setOnClickListener(this);
        tvAlbum.setOnClickListener(this);
        tvPreview.setOnClickListener(this);

        photoAdapter = new PhotoSelectorAdapter(getApplicationContext(), new ArrayList<PhotoModel>(),
                CommonUtils.getWidthPixels(this), this, this, this);
        gvPhotos.setAdapter(photoAdapter);

        albumAdapter = new AlbumAdapter(getApplicationContext(), new ArrayList<AlbumModel>());
        lvAblum.setAdapter(albumAdapter);
        lvAblum.setOnItemClickListener(this);

        findViewById(R.id.bv_back_lh).setOnClickListener(this);

        photoSelectorDomain.getReccent(reccentListener);
        photoSelectorDomain.updateAlbum(albumListener);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_right_lh){
            isScanPhoto=false;
            if(selected==null||selected.size()==0){
                Toast.makeText(this,"您还没有选择任何照片",Toast.LENGTH_SHORT).show();
                return;
            }
           if(KFWActivityCenter.getInstance().getTakephoto_state() == 1){
               priview();

           }else{
               compressedPicshow();
           }


//            if(KFWActivityCenter.getInstance().getTakephoto_state() == 1){
//                priview();
//            }
//            else{
//                ok();
//            }
        }
        else if (v.getId() == R.id.tv_album_ar)
            album();
        else if (v.getId() == R.id.tv_preview_ar){
            isScanPhoto=true;
            if(selected==null||selected.size()==0){
                Toast.makeText(this,"您还没有选择任何照片",Toast.LENGTH_SHORT).show();
                return;
            }
            priview();
           // compressedPicshow();
        }
        else if (v.getId() == R.id.tv_camera_vc)
            catchPicture();
        else if (v.getId() == R.id.bv_back_lh){
            File file = new File("/sdcard/Image_kuai/");
            BasePhotoPreviewActivity.recursionDeleteFile(file);
            finish();}
    }

    private void catchPicture() {
        CommonUtils.launchActivityForResult(this, new Intent(MediaStore.ACTION_IMAGE_CAPTURE), REQUEST_CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
            if (!KFWTools.getSDCard()) { // 检测sd是否可用
                ToastView_custom toast = new ToastView_custom(this);
                toast.showCustom(this, "无SD卡，请检测SD卡是否安装");
                return;
            }
//            new DateFormat();
//            String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".png";

            Bundle bundle = data.getExtras();
            Bitmap bitmap = (Bitmap) bundle.get("data");
            isTake=true;

            compressedPicshow(bitmap);
//            FileOutputStream b = null;
//            File file = new File("/sdcard/Image/");
//            file.mkdirs();// 创建文件夹
//            String fileName = "/sdcard/Image/" + name;
//            try {
//                b = new FileOutputStream(fileName);
//                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            } finally {
//                try {
//                    b.flush();
//                    b.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
          //  }
//            PhotoModel photoModel = new PhotoModel(fileName);
//            selected.clear();
//            selected.add(photoModel);

     //       compressedPicshow();
            //ok();
        }
        if(requestCode == 200 && resultCode == 100){
            setResult(60);
            finish();
        }
        if(requestCode == 200 && resultCode == 70){//预览之后返回的
           // selected.clear();
            reset();
            //photoAdapter.
            for (int i=0;i<photoAdapter.getCount();i++){
                PhotoModel photoModel=(PhotoModel)photoAdapter.getItem(i);
                photoModel.setChecked(false);
            }

            photoAdapter.notifyDataSetChanged();

        }

        if(requestCode == 200 && resultCode == 110){
            reset();
            scanList=(ArrayList<PhotoModel>)data.getExtras().getSerializable("scanphotos");
            for (int i=0;i<photoAdapter.getCount();i++){
                PhotoModel photoModel=(PhotoModel)photoAdapter.getItem(i);
                photoModel.setChecked(false);
                for(int j=0;j<scanList.size();j++){
                    if(scanList.get(j).getOriginalPath().equals(photoModel.getOriginalPath())){
                        selected.add(photoModel);
                        photoModel.setChecked(true);
                        tvPreview.setEnabled(true);
                        tvPreview.setText("预览(" + selected.size() + ")");
                    }
                }

            }
//            if (selected.isEmpty()) {
//                tvPreview.setEnabled(false);
//                tvPreview.setText("预览");
//            }
            photoAdapter.notifyDataSetChanged();
        }

    }

    public String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor.moveToFirst()) {

            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }

    private void ok() {
        if (selected.isEmpty()) {
            setResult(RESULT_CANCELED);
        } else {
            Intent data = new Intent();
            Bundle bundle = new Bundle();
            bundle.putSerializable("photos", selected);
            data.putExtras(bundle);
            setResult(50, data);
        }
        finish();
    }

    private void priview() {
        if(KFWActivityCenter.getInstance().getTakephoto_state() == 1){
            Bundle bundle = new Bundle();
            bundle.putSerializable("photos", selected);
            Intent intent = new Intent(this, PhotoPreviewActivity.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, 200);
        }else{
            Bundle bundle = new Bundle();
            bundle.putSerializable("photos", selected);
            Intent intent = new Intent(this, PhotoPreviewActivity.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, 200);
           // CommonUtils.launchActivity(this, PhotoPreviewActivity.class, bundle);

        }
    }

    private void album() {
        if (layoutAlbum.getVisibility() == View.GONE) {
            popAlbum();
        } else {
            hideAlbum();
        }
    }


    private void popAlbum() {
        layoutAlbum.setVisibility(View.VISIBLE);
        new AnimationUtil(getApplicationContext(), R.anim.translate_up_current).setLinearInterpolator().startAnimation(
                layoutAlbum);
    }


    private void hideAlbum() {
        new AnimationUtil(getApplicationContext(), R.anim.translate_down).setLinearInterpolator().startAnimation(
                layoutAlbum);
        layoutAlbum.setVisibility(View.GONE);
    }


    private void reset() {
        selected.clear();
        tvPreview.setText("预览");
        tvPreview.setEnabled(false);
    }

    @Override
    public void onItemClick(int position) {
        Bundle bundle = new Bundle();
        if (tvAlbum.getText().toString().equals(RECCENT_PHOTO)){
            bundle.putInt("position", position - 1);
        }
        else{
            bundle.putInt("position", position);
        }
        bundle.putString("album", tvAlbum.getText().toString());
        CommonUtils.launchActivity(this, PhotoPreviewActivity.class, bundle);
    }

    @Override
    public void onCheckedChanged(PhotoModel photoModel, CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            selected.add(photoModel);
            tvPreview.setEnabled(true);
        } else {
            selected.remove(photoModel);
        }
        tvPreview.setText("预览(" + selected.size() + ")");

        if (selected.isEmpty()) {
            tvPreview.setEnabled(false);
            tvPreview.setText("预览");
        }

        KFWActivityCenter.getInstance().setArray_model(selected);
    }

    @Override
    public void onBackPressed() {
        if (layoutAlbum.getVisibility() == View.VISIBLE) {
            hideAlbum();
        } else
            super.onBackPressed();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        AlbumModel current = (AlbumModel) parent.getItemAtPosition(position);
        for (int i = 0; i < parent.getCount(); i++) {
            AlbumModel album = (AlbumModel) parent.getItemAtPosition(i);
            if (i == position)
                album.setCheck(true);
            else
                album.setCheck(false);
        }
        albumAdapter.notifyDataSetChanged();
        hideAlbum();

        tvAlbum.setText(current.getName());

        if (current.getName().equals(RECCENT_PHOTO))
            photoSelectorDomain.getReccent(reccentListener);
        else
            photoSelectorDomain.getAlbum(current.getName(), reccentListener); // ��ȡѡ��������Ƭ
    }


    public interface OnLocalReccentListener {
        public void onPhotoLoaded(List<PhotoModel> photos);
    }


    public interface OnLocalAlbumListener {
        public void onAlbumLoaded(List<AlbumModel> albums);
    }

    private OnLocalAlbumListener albumListener = new OnLocalAlbumListener() {
        @Override
        public void onAlbumLoaded(List<AlbumModel> albums) {
            albumAdapter.update(albums);
        }
    };

    private OnLocalReccentListener reccentListener = new OnLocalReccentListener() {
        @Override
        public void onPhotoLoaded(List<PhotoModel> photos) {
            if (tvAlbum.getText().equals(RECCENT_PHOTO))
                photos.add(0, new PhotoModel());
            photoAdapter.update(photos);
            gvPhotos.smoothScrollToPosition(0); // 滚动到顶端
            reset();
        }
    };

    /**
     * 压缩图片
     */

    private  ProgressDialog  progressDialog=null;
    public void compressedPicshow(){
        progressDialog=new ProgressDialog(PhotoSelectorActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setTitle("图片正在处理中");
        progressDialog.setMessage("请稍后。。。");
        progressDialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条

        progressDialog.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < selected.size(); i++) {
                        PhotoModel model = selected.get(i);
                        PhotoModel comModel=compressedPic(model.getOriginalPath(),i);
                        if(comModel!=null){
                            selected.remove(i);
                            selected.add(i,comModel);
                        }

                    }

                    handler.sendEmptyMessage(1);


                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }).start();





    }
    public void compressedPicshow(final Bitmap bitmap){
        progressDialog=new ProgressDialog(PhotoSelectorActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setTitle("图片正在处理中");
        progressDialog.setMessage("请稍后。。。");
        progressDialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
       // progressDialog.setIcon(R.drawable.ic_launcher);
        progressDialog.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    compressedPic(bitmap);
        //            handler.sendEmptyMessage(2);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }).start();





    }
    private boolean isTake=false;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    progressDialog.dismiss();
                    if(KFWActivityCenter.getInstance().getTakephoto_state() == 1){
                        priview();
                    }else{
                        if(isScanPhoto){
                            priview();
                        }else{
                            ok();
                        }

                    }
                    break;
                    case 2:
                        progressDialog.dismiss();
                        ok();
                        break;
            }
        }
    };

    /**
     * 本地图片压缩再上传
     * @param picPath
     */
   // private  Bitmap image=null;



    public  static PhotoModel compressedPic(String picPath, int id){
        String  picid=id+"";
        byte data[]=readBinaryFile(picPath);
        FileOutputStream b = null;
        ByteArrayOutputStream baos =null;
        try {

            if(data.length/1024<=1024){
              return null;
            }
            baos = new ByteArrayOutputStream();
            Bitmap bitmap = null;
            // 取得图片
            InputStream is = new FileInputStream(picPath);
            BitmapFactory.Options options = new BitmapFactory.Options();
            // 这个参数代表，不为bitmap分配内存空间，只记录一些该图片的信息（例如图片大小）
            options.inJustDecodeBounds = true;
            // 通过创建图片的方式，取得options的内容（这里就是利用了java的地址传递来赋值）
            Bitmap map=BitmapFactory.decodeStream(is, null, options);
            // 关闭流
            is.close();
            int i = 0;
            while (true) {
                // 这一步是根据要设置的大小，使宽和高都能满足

                if ((options.outWidth >> i <= 720)
                        && (options.outHeight >> i <= 1280)) {
                    // 重新取得流，注意：这里一定要再次加载，不能二次使用之前的流！
                    is = new FileInputStream(picPath);
                    // 这个参数表示 新生成的图片为原始图片的几分之一。
                    options.inSampleSize =(int) Math.pow(2.0D, i);
                    // 这里之前设置为了true，所以要改为false，否则就创建不出图片
                    options.inJustDecodeBounds = false;
                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                    // 同时设置才会有效s
                    options.inPurgeable = true;
                    // 当系统内存不够时候图片自动被回收
                    options.inInputShareable = true;
                    // 创建Bitmap
                    bitmap = BitmapFactory.decodeStream(is, null, options);
                    break;
                }
                i += 1;
            }

            bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);
                    int newlength=baos.toByteArray().length/1024;
                if(newlength>1024){
                    bitmap=imageZoom(bitmap,1024);
                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);
                }

                int lastlength=baos.toByteArray().length/1024;
                new DateFormat();
                String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))+picid + ".jpg";
                File file = new File("/sdcard/Image_kuai/");
                file.mkdirs();// 创建文件夹
                String fileName = "/sdcard/Image_kuai/" + name;
                b = new FileOutputStream(fileName);
                //1   newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                if(newlength>0){
                    b.write(baos.toByteArray());
                }
               // scanPhotos(fileName,this);

                PhotoModel photoModel = new PhotoModel(fileName);



                return photoModel;

//            }else{
//                return  null;
//            }


        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            try {
                if(b!=null){
                    b.flush();
                    b.close();
                }

                if(baos!=null){
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;


    }


    /**
     * 缩放图片到固定文件大小
     *
     * @param bm
     *            需要缩放的图片
     * @param maxSize
     *            目标文件大小，单位：KB
     * @return
     */
    public static Bitmap imageZoom(Bitmap bm, double maxSize) {
        // 图片允许最大空间 单位：KB
        // 将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        // 将字节换成KB
        double mid = b.length / 1024;
        // 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
        if (mid > maxSize) {
            // 获取bitmap大小 是允许最大大小的多少倍
            double i = mid / maxSize;
            // 开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍
            // 保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小
            bm = zoomImage(bm, bm.getWidth() / Math.sqrt(i), bm.getHeight()
                    / Math.sqrt(i));
        }
        return bm;
    }

    /***
     * 图片的缩放方法
     *
     * @param bgimage
     *            ：源图片资源
     * @param newWidth
     *            ：缩放后宽度
     * @param newHeight
     *            ：缩放后高度
     * @return
     */
    public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
                                   double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }


    public static byte[] readBinaryFile(String picPath){
    BufferedInputStream bis=null;
    ByteArrayOutputStream baos =new ByteArrayOutputStream();
    File file=new File(picPath);
    if(file.exists()){
        try {
            bis=new BufferedInputStream(new FileInputStream(file));
            int len =0;
            byte[] buf=new byte[1024*8];
            while((len=bis.read(buf))!=-1){
                baos.write(buf,0,len);
                baos.flush();
            }
            return baos.toByteArray();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(bis!=null){
                   bis.close();
                }

                if(baos!=null){
                   baos.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

      return  null;
   }
    /**
     * 压缩相机拍照获得的图片
     * @param bitmap
     */
    public  void compressedPic(Bitmap bitmap){
        FileOutputStream b = null;
        int newlength=0;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);
            int per=100;
            if(baos.toByteArray().length/1024>1024){
                while(baos.toByteArray().length/1024>1024){
                    per-=10;
                    if(per<0){
                        per=5;
                    }
                    baos.reset();
                    bitmap.compress(Bitmap.CompressFormat.JPEG,per,baos);
                    if(per==5){
                        break;
                    }

                }
                newlength=baos.toByteArray().length/1024;
                if(bitmap!=null&&!bitmap.isRecycled()){
                    bitmap=null;
                    System.gc();
                }
             //   ByteArrayInputStream isBm=new ByteArrayInputStream(baos.toByteArray());

                new DateFormat();
                String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
                File file = new File("/sdcard/Image_kuai/");
                file.mkdirs();// 创建文件夹
                String fileName = "/sdcard/Image_kuai/" + name;
                b = new FileOutputStream(fileName);

                if(newlength>0){
                    b.write(baos.toByteArray());//写入内存卡
                }
               // scanPhotos(fileName,this);

                PhotoModel photoModel = new PhotoModel(fileName);
                selected.clear();
                selected.add(photoModel);
                handler.sendEmptyMessage(2);
//                return;

            }else{
              newlength=baos.toByteArray().length/1024;
            new DateFormat();
            String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
            File file = new File("/sdcard/Image_kuai/");
            file.mkdirs();// 创建文件夹
            String fileName = "/sdcard/Image_kuai/" + name;
            b = new FileOutputStream(fileName);

            if(newlength>0){
                b.write(baos.toByteArray());
            }
           // scanPhotos(fileName,this);

            PhotoModel photoModel = new PhotoModel(fileName);
            selected.clear();
            selected.add(photoModel);
            handler.sendEmptyMessage(2);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            try {
                if(b!=null){
                    b.flush();
                    b.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }




    }
    /**

     * 扫描、刷新相册

     */
    public static void scanPhotos(String filePath, Context context) {

        Intent intent = new Intent(

                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);

        Uri uri = Uri.fromFile(new File(filePath));

        intent.setData(uri);
        context.sendBroadcast(intent);

    }




}
